<template>
  <div class="search-contain">
    <form action="/" class="search-box">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @click="resultShow = false"
        background="#3296fa"
        shape="round"
      />
    </form>
    <!-- 搜索结果 -->

    <search-result v-if="resultShow" :search-text="searchText" />
    <!-- 搜索建议 -->

    <search-suggestion
      v-else-if="searchText"
      @search="onSearch"
      :search-text="searchText"
    />
    <!-- 搜索历史 -->
    <search-history
      v-else
      :search-history="searchHistories"
      @search="onSearch"
    />
  </div>
</template>
<script>
import SearchHistory from "./components/search-history.vue";
import SearchResult from "./components/search-result.vue";
import SearchSuggestion from "./components/search-suggestion.vue";
import { setItem, getItem } from "@/utils/storage";
export default {
  name: "search",
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult,
  },
  data() {
    return {
      searchText: "",
      resultShow: false,
      searchHistories: getItem("TOUTIAO_HISTORY") || [],
    };
  },
  methods: {
    onSearch(val) {
      let idx = this.searchHistories.findIndex((item) => item === val);
      if (idx !== -1) this.searchHistories.splice(idx, 1);
      this.searchHistories.unshift(val);
      this.searchText = val;
      this.resultShow = true;
    },
    onCancel() {
      // Toast("取消");
    },
  },
  watch: {
    // 数据持久化
    searchHistories: {
      deep: true,
      handler() {
        setItem("TOUTIAO_HISTORY", this.searchHistories);
      },
    },
  },
};
</script>

<style lang='less' scoped>
.van-search__action {
  color: aliceblue;
}
.search-box {
  position: sticky;
  top: 0;
  z-index: 1000;
}
</style>